/**
 * File UdpReceiver.java 
 */
package cs.ni;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Observable;

/**
 * Listens on udp port for incoming messages.<br>
 * Is always listening so need to be a thread
 * keep ChatNi notified of new message arrival. <p>
 * Package  cs.ni
 * Project ChatSystemG1 - INSA 4INFOA1 - 2013/2014
 * @author Julie DUMONS & Juste OUEDRAOGO
 */
public class UdpReceiver extends Observable implements Runnable{
	
	/**
	 * Socket used for udp reception
	 */
	private DatagramSocket socket;
	
	/**
	 * Constructor of UdpReceiver
	 * @param socket 
	 */
	public UdpReceiver(DatagramSocket socket){
			this.socket = socket;	
	}
	
	/**
	 * receive message on udp port (LocalUser.udpListeningPort)
	 * waits for new message and process it
	 * @return received message
	 */
	public void receive(){
		byte[] buf=new byte[4048];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);

		 // wait for a packet
		try {
			socket.receive(packet);
			if(packet.getLength()!=0){
				setChanged();
				notifyObservers(packet);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
		
	}
	
	

	/**
	 * listens for incoming messages on LocalUser.udpListeningPort
	 * when a message arrives, processes it and return back to listening
	 */
	@Override
	public void run() {
		while(!Thread.currentThread().isInterrupted())
			receive();	
	}

}
